#include "list.h"

void list::Insert(int _d){
	node* pNew = new node;
	pNew->setData(_d);
	
	if(pHead == NULL){
		pHead = pNew;
		pTail = pNew;
	}
	else{ 
		pTail->setNext(pNew);
		pNew->setRear(pTail);
		pTail = pNew;
	}

}

void list::Delete(int _d){
	node* pCur = pHead;
	node* pPre = pCur;
	node* ptemp = NULL;
	if(pHead == NULL){
		cout<<"pHead is NULL!"<<endl;
		return;
	}

	if(pHead->getData() == _d){
		pHead = pHead->getNext();
		pHead->setRear(NULL);
		delete pCur;
		return;
	}
	
	else if(pTail->getData() == _d){
		pCur = pTail;		
		pTail = pTail->getRear();
		pTail->setNext(NULL);
		delete pCur;
		return;
	}
	
	//target delete data is not head or tail;	
	while(pCur){
		if(pPre->getData() == _d){
			break;
		}
		pPre = pCur;
		pCur = pCur->getNext();	
	}

	pPre->getRear()->setNext(pPre->getNext() );	
	pPre->getNext()->setRear(pPre->getRear() );
	delete pPre;


}


void list::print(){
	node* pCur = pHead;
	node* pPre = pCur;
	cout<<"=====PRINT Data====="<<endl;

	while(pPre != pTail){
		cout<<pCur->getData()<<" ";
		pPre = pCur;
		pCur = pCur->getNext();
		cout<<endl;
	}

}

void list::swap_data(int a, int b){
	node* pCur = pHead;
	node* pPre = pCur;
	node* target_a = NULL;
	node* target_b = NULL;
	

	//search target.
	while(pCur){
		pPre = pCur;
		pCur = pCur->getNext();		
		if(pPre->getData() == a)
			target_a = pPre;
		if(pPre->getData() == b)
			target_b = pPre;
		
	}	

	if(target_a == NULL || target_b == NULL){
		cout<<"data search fail"<<endl;
		return;		
	}


	if(target_a->getNext() == target_b || target_b->getNext() == target_a){ //인접시
		target_a->setNext(target_b->getNext());
		target_b->setRear(target_a->getRear());

		if(target_a->getRear() != NULL){
			target_a->getRear()->setNext(target_b);
		}

		if(target_b->getNext() != NULL){
			target_b->getNext()->setRear(target_a);
		}
	
		target_b->setNext(target_a);
		target_a->setRear(target_b);
	}

	else{ //비인접시
		node* temp_a_next = target_a->getNext();
		node* temp_b_rear = target_b->getRear();

		target_a->getNext()->setRear(target_b);
		target_b->getRear()->setNext(target_a);
		if(target_a->getRear() != NULL){
			target_a->getRear()->setNext(target_b);
			target_b->setRear(target_a->getRear());			
		}	
		if(target_b->getNext() != NULL){
			target_b->getNext()->setRear(target_a);
			target_a->setNext(target_b->getNext());
		}
		target_b->setNext(temp_a_next);
		target_a->setRear(temp_b_rear);
		
	}
	
	if(target_a == pHead)
		pHead = target_b;
	if(target_b == pTail)
		pTail = target_a;
	


	
}

void list::sort(){
	node* pCur = pHead;
	node* pPre = pCur;
	
	while(pPre != pTail){
		if(pPre->getData() > pPre->getNext()->getData() ){
			swap_data(pPre->getData(),pPre->getNext()->getData() );
			pCur = pHead;
			pPre = pCur;
		}
		pPre = pCur;
		pCur = pCur->getNext();

	}


}
